<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<!-- 基本信息 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillId_FormItem" prop="Entity.BillId">
								<template #label>
									<WtmLabelTooltip label="采购申请单" tooltip="关联的采购申请单主表" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.BillId" disabled class="width100">
									<el-option v-for="item in stateData.AllSysPurchaseRequestBills" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_PurchaseProgress_FormItem" prop="Entity.PurchaseProgress">
								<template #label>
									<WtmLabelTooltip label="采购进度" tooltip="该明细行的采购进度状态" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.PurchaseProgress" disabled class="width100">
									<el-option key="采购审批中" value="采购审批中" label="采购审批中"></el-option>
									<el-option key="采购需求池" value="采购需求池" label="采购需求池"></el-option>
									<el-option key="采购中" value="采购中" label="采购中"></el-option>
									<el-option key="运输中" value="运输中" label="运输中"></el-option>
									<el-option key="已完成" value="已完成" label="已完成"></el-option>
									<el-option key="已取消" value="已取消" label="已取消"></el-option
								></el-select>
							</el-form-item>
						</el-col> -->
					</el-row>
				</div>

				<!-- 物料信息 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>物料信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :span="24" class="mb20">
							<el-form-item ref="Entity_MaterialSkuId_FormItem" prop="Entity.MaterialSkuId">
								<template #label>
									<WtmLabelTooltip label="物料SKU" tooltip="采购的物料SKU" />
								</template>
								<WtmMaterialSelector
									v-model="stateData.vmModel.Entity.MaterialSkuId"
									disabled
									placeholder="物料SKU"
									label-format="{MaterialName}({MaterialCode}) - {SkuName}({SkuCode})"
									returnResultFields="Sku"
									:isPurchaseScenario="true"
									@change="handleMaterialSkuSelect"
								/>
							</el-form-item>
						</el-col>

						<!-- 展示已选规格信息 -->
						<el-col :span="24" class="mb20" v-if="selectedSkuInfo">
							<el-form-item>
								<template #label>
									<WtmLabelTooltip label="已选规格" tooltip="当前选择的物料规格信息" />
								</template>
								<div class="sku-info-display">
									<el-tag type="info" style="margin-right: 8px">{{ selectedSkuInfo.materialName }}</el-tag>
									<el-tag v-for="attr in selectedSkuInfo.attributes" :key="attr.id" type="success" style="margin-right: 8px">
										{{ attr.name }}: {{ attr.value }}
									</el-tag>
								</div>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_IsBackupMaterial_FormItem"
								prop="Entity.IsBackupMaterial"
								:rules="[{ required: true, message: '是否备用物资为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="是否备用物资" tooltip="备用物资不计入物料呆滞考核" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.IsBackupMaterial" disabled class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 数量和金额 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>数量和金额</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="8" class="mb20">
							<el-form-item
								ref="Entity_RequestQuantity_FormItem"
								prop="Entity.RequestQuantity"
								:rules="[{ required: true, message: '申请数量为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="申请数量" tooltip="物料的申请采购数量" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.RequestQuantity" disabled class="width100"></el-input-number>
							</el-form-item>
						</el-col>

						<!-- <el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BudgetAmount_FormItem" prop="Entity.BudgetAmount">
										<template #label>
											<WtmLabelTooltip label="预算金额" tooltip="该物料的预算金额" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.BudgetAmount" disabled class="width100"></el-input-number>
									</el-form-item>
								</el-col> -->
					</el-row>
				</div>

				<!-- 需求说明 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>需求说明</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_RequiredArrivalDate_FormItem"
								prop="Entity.RequiredArrivalDate"
								:rules="[{ required: true, message: '要求到货日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="要求到货日期" tooltip="该物料期望的到货日期" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.RequiredArrivalDate"
									disabled
									class="width100"
									placeholder="请选择要求到货日期"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_TechnicalRequirement_FormItem" prop="Entity.TechnicalRequirement">
								<template #label>
									<WtmLabelTooltip label="技术要求" tooltip="物料的技术规格和要求说明，超过500字建议上传技术文件" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.TechnicalRequirement"
									type="textarea"
									:rows="3"
									disabled
									placeholder="请输入技术要求和规格说明"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 附件信息 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>附件信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :span="24" class="mb20">
							<el-form-item ref="SelectedFilesIds_FormItem" prop="SelectedFilesIds">
								<template #label>
									<WtmLabelTooltip label="附件" tooltip="明细行关联的附件文件，如技术文件、图纸等" />
								</template>
								<wtm-upload-file v-model="stateData.vmModel.SelectedFilesIds" disabled class="width100"></wtm-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysPurchaseRequestBillEntryApi as api } from '/@/views/supplychain/syspurchaserequestbillentry/api';
import other from '/@/utils/other';
import { ISysPurchaseRequestBillEntryVm } from '/@/views/supplychain/syspurchaserequestbillentry/api/interface';
import { ISysSelectType, IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();

// 存储选中的 SKU 完整信息用于展示
const selectedSkuInfo = ref<{
	materialName: string;
	attributes: Array<{ id: string; name: string; value: string }>;
} | null>(null);

const stateData = reactive<IViewModel<ISysPurchaseRequestBillEntryVm>>({
	vmModel: {
		Entity: {
			ID: null,
			BillId: null,
			MaterialId: null,
			MaterialSkuId: null,
			IsBackupMaterial: false,
			RequestQuantity: null,
			UnitPrice: null,
			TotalAmount: null,
			BudgetAmount: null,
			TechnicalRequirement: null,
			RequiredArrivalDate: null,
			PurchaseProgress: null,
			Files: null,
		},
		SelectedFilesIds: [],
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysPurchaseRequestBills: [] as ISysSelectType[],
	AllSysMaterials: [] as ISysSelectType[],
	AllSysMaterialSkus: [] as ISysSelectType[],
});

// 取消
const onClose = () => {
	closeDialog();
};

/**
 * 处理物料SKU选择（详情页面不可编辑，但保留接口用于组件兼容性）
 * @param value - SKU ID
 * @param data - SKU完整数据
 */
const handleMaterialSkuSelect = (value: string | null, data: any) => {
	// 详情页面禁用编辑，此函数仅为保持组件接口一致性
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other
			.getSelectList('/api/SysPurchaseRequestBillEntry/GetSysPurchaseRequestBills', [], false)
			.then((x) => (stateData.AllSysPurchaseRequestBills = x)),
		other.getSelectList('/api/SysPurchaseRequestBillEntry/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x)),
		other.getSelectList('/api/SysPurchaseRequestBillEntry/GetSysMaterialSkus', [], false).then((x) => (stateData.AllSysMaterialSkus = x)),
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => other.setValue(stateData.vmModel, x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
